package com.parking.common.web.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.parking.common.core.model.StateData;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
@ConfigurationProperties(prefix = "aliyun.oss")
@Data
public class OssUtil {
    private String host;

    private String accessId;

    private String accessSecret;

    private String bucketName;

    public String uploadFile(InputStream file, String name) {
        //创建客户端对象
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //上传
            ossClient.putObject(bucketName, name, file);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return "https://" + bucketName + "."+ host + "/"+name;
    }

    public String uploadFile(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String name = UUID.randomUUID().toString();
        assert filename != null;
        filename = name + filename.substring(filename.lastIndexOf("."));

        return uploadFile(file.getInputStream(),filename);
    }

    public boolean deleteFile(String name) {
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //删除文件
            ossClient.deleteObject(bucketName, name);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return true;
    }
}
